package edu.qqcui.study.condition;

import edu.qqcui.study.bean.Blue;
import edu.qqcui.study.bean.RainBow;
import edu.qqcui.study.bean.Red;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * 实现Import的手动注入Bean
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021-06-26 14:45
 **/
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * Register bean definitions as necessary based on the given annotation metadata of
	 * the importing {@code @Configuration} class.
	 * <p>Note that {@link BeanDefinitionRegistryPostProcessor} types may <em>not</em> be
	 * registered here, due to lifecycle constraints related to {@code @Configuration}
	 * class processing.
	 * <p>The default implementation is empty.
	 *
	 * @param importingClassMetadata annotation metadata of the importing class
	 * @param registry               current bean definition registry
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		boolean hasRed = registry.containsBeanDefinition(Red.class.getName());
		boolean hasBlue = registry.containsBeanDefinition(Blue.class.getName());

		if (hasRed && hasBlue) {
			// 向容器中注册RainBow的实例信息
			// 构造BeanDefinition信息
			RootBeanDefinition definition = new RootBeanDefinition(RainBow.class);
			registry.registerBeanDefinition("rainBow", definition);
		}
	}
}
